package com.xxkj.redis.lock;

import com.xxkj.redis.model.LockInfo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class FairLock implements Lock {

    private  RLock rLock;
    
    private final LockInfo lockInfo;

    private RedissonClient redissonClient;

    public FairLock(RedissonClient redissonClient,LockInfo info) {
        this.redissonClient = redissonClient;
        this.lockInfo = info;
    }

    /**
     * 基于redis加锁
     * @return
     */
    @Override
    public boolean acquire() {
        try {
            //公平锁，获取锁名称
            rLock=redissonClient.getFairLock(lockInfo.getName());
            //尝试加锁，加锁最多等待waitime，上锁leasetime后释放锁
            return rLock.tryLock(lockInfo.getWaitTime(), lockInfo.getLeaseTime(), TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            return false;
        }
    }

    /**
     * 基于redis释放锁
     * @return
     */
    @Override
    public boolean release() {
        //当前线程是否保持此锁定
        if(rLock.isHeldByCurrentThread()){

            try {
                //redission强制解锁，释放锁
                return rLock.forceUnlockAsync().get();
            } catch (InterruptedException e) {
                return false;
            } catch (ExecutionException e) {
                return false;
            }
        }
        return false;
    }
}
